package ups.MapParse;

import java.util.HashSet;
import java.util.ArrayList;
import java.util.Collections;

/* Implements Blob Searching Algorithm */
public class ArrowFinder {
	
	// Magic Numbers!
	private int blueColor = -16776961;
	private final int minimumArrowPixels = 30;
	
	// Date Structures
	private ArrayList<HashSet<Point>> store;
	private ArrayList<Point> arrowLocations;
	
	public ArrowFinder( int[] imageData, int width, int height ) {
		store = new ArrayList<HashSet<Point>>();
		
		int X, Y;
		
		for( Y = 0; Y < width; Y++ ) {
			for( X = 0; X < width; X++) {
				int val = imageData[ Y * width + X];
				if( val == blueColor ) {
				//	System.out.println( X + ", " + Y );
					int leftVal = imageData[ Y * width + (X - 1)];
					int topVal = imageData[ (Y-1) * width + X ];
					Point leftPoint = new Point (X-1, Y );
					Point topPoint = new Point( X, Y-1);
					Point thisPoint = new Point( X, Y );
					
					if( val == leftVal ) {
						HashSet<Point> leftSet = setForPoint( leftPoint );
						leftSet.add( thisPoint  );
						if( Y >= 1 && val == topVal ) {
							HashSet<Point> topSet = setForPoint( topPoint );
							if( topSet != leftSet ) {
								leftSet.addAll( topSet );
								store.remove( topSet );
							} else {
							}
						}
					} else if( Y >= 1 && val == topVal ) {
						HashSet<Point> topSet = setForPoint( topPoint );
						topSet.add( thisPoint );
					} else {
						HashSet<Point> nSet = new HashSet<Point>();
						nSet.add( thisPoint );
						store.add( nSet );
					}
				}
			}
		}
		
		arrowLocations = new ArrayList<Point>();
		for( HashSet<Point> set : store ) {
			if( set.size() > minimumArrowPixels ) {
				for( Point p : set ) {
					imageData[ p.y * width + p.x] = Pixel.whitePixel.intValue; // Clear out these pixels!
				}
				
				ArrayList<Point> sortedSet = Collections.list( Collections.enumeration( set ));
				Collections.sort( sortedSet , new PointComparator() );
				int a = 0;
				int b = 0;
				for( Point p : sortedSet ) {
					a += p.x;
					b += p.y;
				}
				
				a = a / sortedSet.size();
				b = b / sortedSet.size();
				
				arrowLocations.add( new Point( a, b ));
			}
		}
	}

	private HashSet<Point> setForPoint( Point p ) {
		for( HashSet<Point> set : store ) {
			if( set.contains( p ) ) {
				return set;
			}
		}
		return null;
	}
	
	public ArrayList<Point> getArrowLocations() {
		return arrowLocations;
	}
}
